// Define the namespace
jmaki.namespace("jmaki.widgets.yahoo.autocomplete");

/**
 * Yahoo UI Autocomplete Widget
 *
 * @author Edwin Goei
 * @author Greg Murray
 * @constructor
 * @see http://developer.yahoo.com/yui/autocomplete/
 */
 
jmaki.widgets.yahoo.autocomplete.Widget = function(wargs) {
	
    var _widget = this;
    var publish = "/yahoo/autocomplete";
    var subscribe = ["/yahoo/autocomplete"];
    var uuid = wargs.uuid; 
    var service = wargs.service;
    var containerId = uuid + "_container";
    var container = document.getElementById(wargs.uuid);
    var inputContainer = document.getElementById(wargs.uuid + "_autocomplete");
;
    var autoComp;

    var vmappings = {};
    var counter=0;
    var ds;
    var completionMethod;

    if (wargs.args && wargs.args.completionMethod) {
    	completionMethod = wargs.args.completionMethod;
    }
    
    if (wargs.publish) {
		publish = wargs.publish;
	}
	
    if (wargs.subscribe){
        if (typeof wargs.subscribe == "string") {
            subscribe = [];
            subscribe.push(wargs.subscribe);
        } else {
            subscribe = wargs.subscribe;
        }
    }
    function genKey(){
        return wargs.uuid + "_item_" + counter++;
    }
    
    function modelConverter(data) {
    	if (data.items) {
    		data = data.items;
    	}
        var model = [];
        for (var i=0; i < data.length; i++) {
            var _val = data[i].value;
            var _label = data[i].label;
            // if only a value is specified make the label equal to the value
            if (!_val && _label) _val = _label;
            if (_val && !_label) _label = _val;
            if (data[i].selected &&  data[i].selected == true) {
               _widget.selected = _label;             
            }

            var key =  data[i].id;
            if (!key) key = genKey();
            vmappings[_val] = { targetId : key, action : data[i].action};
            model.push([_label,_val]);
                
        }
        return model;
    }    



    this.init = function() {
        var acContainer = document.getElementById(wargs.uuid + "_container");
        acContainer.style.width = inputContainer.clientWidth + "px"
        _widget.nativeWidget = new YAHOO.widget.AutoComplete(uuid
				+ "_autocomplete", uuid + "_container", ds);
		_widget.nativeWidget.prehighlightClassName = "yui-ac-prehighlight";
		_widget.nativeWidget.typeAhead = true;
		_widget.nativeWidget.useShadow = true;
		_widget.nativeWidget.forceSelection = true;
		_widget.nativeWidget.itemSelectEvent.subscribe( function(ev, item, o) {		
			var i = vmappings[item[2][1]];
			processActions(i, i.targetId, item[2][1]);
	    }); 
    };
 
     function doSubscribe(topic, handler) {
        var i = jmaki.subscribe(topic, handler);
        _widget.subs.push(i);
    }
    
    this.destroy = function() {
        for (var i=0; _widget.subs && i < _widget.subs.length; i++) {
            jmaki.unsubscribe(_widget.subs[i]);
        }
    };

    function processActions(m, pid, value) {
    	
        jmaki.processActions(
                { topic :  publish,
                  targetId : pid,
                 widgetId : wargs.uuid,
                 action : m.action,
                 type : 'onSelect',
                 value : value 
                }
               );	
    }     
    
    this.setValues = function(e){  
        var _values;
        if (e.message && e.message.value) _values = e.message.value;
        else _values = e;
        var _selected;
        // clear out the selected value so we can reselect
        _widget.selected = undefined;
        if (_values) {
           vmappings = {};
           _widget.setValue("");
           if (_widget.selected)_widget.setValue(_widget.selected);
           ds = new YAHOO.widget.DS_JSArray(modelConverter(_values));
           // set the new data sources
           this.wrapper.dataSource = ds;
        }
    };    

    this.postLoad = function() {	
        _widget.subs = [];
        if (wargs.args && wargs.args.selected) {        
            _widget.nativeWidget.setValue(wargs.args.selected);     
        } else if (_widget.selected) {
           _widget.setValue(_widget.selected);    
        }
        for (var _i=0; _i < subscribe.length; _i++) {
            doSubscribe(subscribe[_i]  + "/select", _widget.setValue);
            doSubscribe(subscribe[_i]  + "/setValues", _widget.setValues);
        }
	    if (wargs.value) {
	    	 ds = new YAHOO.widget.DS_JSArray(modelConverter(wargs.value));
	    	 _widget.init();
	    } else if (wargs.service && completionMethod == 'server') {  	
	    	ds = new YAHOO.util.XHRDataSource(wargs.service); 
	    	ds.responseType = YAHOO.util.XHRDataSource.TYPE_JSON; 
	    	// schema of the JSON results
	    	ds.responseSchema = { 
	    		        resultsList : "items", 
	    		        fields : ["label", "value", "action", "selected"] 
	    	}; 
	    	_widget.init();
		} else if (wargs.service){
			jmaki.doAjax(
			           {url: wargs.service, 
			            callback: function(req) {
			                   if (req.responseText == "") {
			                       container.innerHTML = "No data provided by: " + wargs.service;
			                       return;
			                    }
			                    var _in = eval('(' + req.responseText + ')');
			                    ds = new YAHOO.widget.DS_JSArray(modelConverter(_in)); 
			                    _widget.init();
			           }
			     }
			);		
		}       
    };

    this.getValue = function() { 
        return inputContainer.value;
    };
    
    this.setValue = function(_n) {
        inputContainer.value = _n;
    };  
};